#include "Core/GsLog.h"
 #include "FileSystem/File.h"
#include "String/String.h"
#include "Core/GlobalSet.h"

BEGIN_GLSX_NAMESPACE

TLogLevel GsLog::eMessageLevel = logINFO;

std::ostringstream& GsLog::Get( TLogLevel level /*= logINFO*/, int line_no/* = __LINE__*/, const char* filename/* = __FILE__*/ )
{
	bool bOn = Glsx::GlobalSet::GetSysCfg("DebugOn", false).asBool();
	if (Glsx::GlobalSet::GetSysCfg("DebugOn", false).asBool())
	{
		EnterCriticalSection(&g_DebugCs);
		eMessageLevel = level;
		//os << " [ " << Level2String(level) << " ] "
		//	<< "(line: " << line_no << ") "
		//	<< "(file: " << filename << ") "
		//	<< "(thid: " << GetCurrentThreadId() << ") ";
	}
	return os;
}

GsLog::~GsLog()
{
	if (Glsx::GlobalSet::GetSysCfg("DebugOn", false).asBool())
	{

		if (eMessageLevel >= GsLog::ReportingLevel())
		{
			os << std::endl;
			if (Glsx::GlobalSet::GetSysCfg("Debug2File", false).asBool())
			{
				Glsx::MMCacheFileWrite(g_hDsFile, os.str().c_str(), os.str().size());
			}
			else
			{
				//fprintf(stderr, "%s", os.str().c_str());
				RETAILMSG(TRUE, (Bstr2Wstr(os.str()).c_str()));
				fflush(stderr);
			}
		}
		LeaveCriticalSection(&g_DebugCs);
	}
}

std::string GsLog::Level2String( TLogLevel level )
{
	switch(level)
	{
	case logERROR:
		return "logERROR";
	case logWARNING:
		return "logWARNING";
	case logINFO:
		return "logINFO";
	}
	return "";
}

TLogLevel& GsLog::ReportingLevel()
{
	return eMessageLevel;
}

GsLog::GsLog()
{
}

GlsxCommon_API int FlushLogFile()
{
	if (g_hDsFile && 
		Glsx::GlobalSet::GetSysCfg("DebugOn", false).asBool() && 
		Glsx::GlobalSet::GetSysCfg("Debug2File", false).asBool())
	{
		EnterCriticalSection(&g_DebugCs);
		MMCacheFileFlush(g_hDsFile);
		LeaveCriticalSection(&g_DebugCs);
	}
	return 0;
}

END_GLSX_NAMESPACE